package utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: bigScaleLoadTest
 * @className: RegistrationCode
 * @description:
 * @author: JLONG
 * @date: 2024/11/6 10:22
 * @version: 1.0
 */
public class EncryptionCode {

    public static void main(String[] args) {

        // 输入 labelID， 控制台输出注册码
//        EncryptionCode.generate("9CB92993", "9CB92994");

        // 输入 csv文件， 文件输出注册码
        EncryptionCode.fileGenerate("/Users/jlong/IdeaProjects/bigScaleLoadTest/labelID.csv", "registrationCode.csv");
    }


    public static void fileGenerate(String labelIDFile, String encryptionCodeFile){
        // 输入文件路径
        String inputFile = labelIDFile;
        // 输出文件路径
        String outputFile = encryptionCodeFile;

        List<String> labelInfo = new ArrayList<>();

        // 读入文件数据
        try (BufferedReader br = new BufferedReader(new FileReader(inputFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 以分号分割每行
                String[] values = line.split(";");
                String tag = "NULL";
                if (values.length > 1) {
                    tag = values[1];
                }
                String[] encryptionInfo = EncryptionCode.generate(values[0]);
                labelInfo.add(encryptionInfo[1] + ";" + tag);
            }

            // 写出数据至文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
            for (String meta : labelInfo) {
                bw.write(meta + "\n");
            }
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

     public static void generate(String... labelIDs) {
        for (String labelID : labelIDs) {
            String[] str = generate(labelID);
            System.out.println(str[0] + ";" + str[1]);
        }
    }

    public static String[] generate(String labelID) {

        String jarFilePath = "/Users/jlong/IdeaProjects/bigScaleLoadTest/lib/CodeGenerator.jar";
        String[] command = {"java", "-jar", jarFilePath, labelID};
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        StringBuilder registrationCode = new StringBuilder();

        try {
            // 启动进程
            Process process = processBuilder.start();
            // 使用bufferedReader 读取标准输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                registrationCode.append(line).append(System.lineSeparator());
            }
            // 等待进程结束并获取退出代码
            int exitCode = process.waitFor();

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        return registrationCode.toString().split(";");
    }
}
